package org.edu.modules.growth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.growth.config.MathTool;
import org.edu.modules.growth.config.QueryConditionTool;
import org.edu.modules.growth.dto.TeacherDTO;
import org.edu.modules.growth.dto.VeJsczUateDTO;
import org.edu.modules.growth.dto.VeJsczUateDetailDTO;
import org.edu.modules.growth.dto.VeJsczUateEditDTO;
import org.edu.modules.growth.entity.VeJsczUate;
import org.edu.modules.growth.entity.VeJsczUateDetail;
import org.edu.modules.growth.mapper.IVeJsczUateDetailMapper;
import org.edu.modules.growth.mapper.IVeJsczUateMapper;
import org.edu.modules.growth.mapper.IVeJsczUateProjectMapper;
import org.edu.modules.growth.service.IVeJsczUateService;
import org.edu.modules.growth.vo.QueryCondition;
import org.edu.modules.growth.vo.TeacherVo;
import org.edu.modules.growth.vo.VeJsczUateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class VeJsczUateServiceImpl extends ServiceImpl<IVeJsczUateMapper,
        VeJsczUate> implements IVeJsczUateService {

    private IVeJsczUateMapper mIVeJsczUateMapper ;

    private IVeJsczUateDetailMapper mIVeJsczUateDetailMapper ;

    private IVeJsczUateProjectMapper mIVeJsczUateProjectMapper ;

    @Override
    public List<TeacherVo> getTeachers() {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(VeJsczUateDTO dto) throws Exception {
        VeJsczUate uate = new VeJsczUate() ;
        VeJsczUateDetail demo = new VeJsczUateDetail() ;
        List<VeJsczUateDetailDTO> items = dto.getDetails() ;
        int all = items.size() ;
        int pass = (int) items.stream().filter(l -> 1 == l.getResult()).count();
        int zb =  MathTool.getPercent(pass,all,0).intValue() ;
        // 获取当前操作用户信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前时间
        Long time = System.currentTimeMillis()/1000 ;

        // 通用信息设置
        uate.setSemId(dto.getSemId())
                .setCreateTime(time)
                .setType(dto.getType())
                .setYearCode(dto.getYearCode())
                .setCreateUserId(Long.parseLong(user.getId()))
                .setPassNum(pass)
                .setProjectNum(all)
                .setScale(zb)
                .setTerminalId(1L);

        demo.setTerminalId(1L).setCreateTime(time).setSemId(dto.getSemId()).setYearCode(dto.getYearCode())
                .setCreateUserId(Long.parseLong(user.getId())) ;

        List<TeacherDTO> teachers = dto.getTeachers();
        Map<String,Object> map = new HashMap<>() ;
        map.put("semId",dto.getSemId()) ;
        for (TeacherDTO teacher : teachers) {
            // 查询考核结果是否存在
            map.put("teacherUserId",teacher.getTeacherUserId()) ;
            List<VeJsczUate> list = mIVeJsczUateMapper.selectByMap(map) ;
            if( !CollectionUtils.isEmpty(list)){
                throw  new Exception("存在教师已考核！");
            }
            uate.setGH(teacher.getGH()).setXM(teacher.getXM())
                    .setTeacherUserId(teacher.getTeacherUserId())
                    .setFalId(teacher.getFalId());
            mIVeJsczUateMapper.insert(uate) ;
            items.forEach(l->{
                demo.setUateId(uate.getId())
                        .setResult(l.getResult())
                        .setProjectId(l.getProjectId())
                        .setTeacherUserId(uate.getTeacherUserId());
                mIVeJsczUateDetailMapper.insert(demo) ;
            });
        }
    }

    @Override
    public Map<String,Object> selectPage(QueryCondition queryCondition ){
        HashMap<String,Object> map = new HashMap<>();
        IPage<VeJsczUate> page = new Page<>(queryCondition.getCurrent(), queryCondition.getPageSize());
        //创建查询的条件
        QueryWrapper<VeJsczUate> wrapper = new QueryWrapper<>() ;
        QueryConditionTool.advancedQueryPage(queryCondition.getConditions(),wrapper);
        wrapper.orderByDesc("id");
        page = mIVeJsczUateMapper.selectPage(page,wrapper);
        //获取数据
        List<VeJsczUate> list = page.getRecords();
        //统计页码
        Integer count = mIVeJsczUateMapper.selectCount(wrapper);
        map.put("list",list);
        map.put("count", count);
        return map;
    }

    @Override
    public VeJsczUateVo getDetailById(Long id) {
        VeJsczUateVo vo = new VeJsczUateVo() ;
        VeJsczUate ve = mIVeJsczUateMapper.selectById(id) ;
        BeanUtils.copyProperties(ve,vo);
        vo.setProjests(mIVeJsczUateProjectMapper.getProjectByUateId(id)) ;
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        mIVeJsczUateMapper.deleteById(id) ;
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("uateId",id) ;
        mIVeJsczUateDetailMapper.deleteByMap(map) ;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeLogicByIds(List<Long> ids) {
        QueryWrapper<VeJsczUate> wrapper = new QueryWrapper<>() ;
        wrapper.in("id",ids) ;
        mIVeJsczUateMapper.delete(wrapper) ;
        QueryWrapper<VeJsczUateDetail> wrapperDetail = new QueryWrapper<>() ;
        wrapperDetail.in("uateId",ids) ;
        mIVeJsczUateDetailMapper.delete(wrapperDetail) ;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(VeJsczUateEditDTO dto,VeJsczUate ve) throws Exception {
        if( !CollectionUtils.isEmpty(dto.getDetails())){
            Integer all = dto.getDetails().size() ;
            int pass = (int) dto.getDetails().stream().filter(l -> 1 == l.getResult()).count();
            Integer zb =  MathTool.getPercent(pass,all,0).intValue() ;
            VeJsczUate uate = new VeJsczUate() ;
            uate.setId(dto.getId()).setProjectNum(all).setPassNum(pass).setScale(zb) ;
            mIVeJsczUateMapper.updateById(ve) ;
            // 考核子项目修改,先清除旧数据，再新增数据
            Map<String,Object> map = Maps.newHashMap() ;
            map.put("uateId",dto.getId()) ;
            mIVeJsczUateDetailMapper.deleteByMap(map) ;
           // 新增
            VeJsczUateDetail detail = new VeJsczUateDetail() ;
            detail.setUateId(dto.getId()).setSemId(ve.getSemId()).setTerminalId(1L).setTeacherUserId(ve.getTeacherUserId())
                    .setYearCode(ve.getYearCode()).setCreateTime(ve.getCreateTime())
            .setCreateUserId(ve.getCreateUserId());
            dto.getDetails().forEach(l->{
                detail.setResult(l.getResult()).setProjectId(l.getProjectId());
                mIVeJsczUateDetailMapper.insert(detail) ;
            });
        }else{
            throw new Exception("考核项为空！");
        }
    }


}
